// const {JSDOM} =  require("jsdom");
const fs = require('fs');
const { request } = require('http');
const https = require("https")
// const dom = new JSDOM(`<!DOCTYPE html>
// <html lang="en">
// <head>
// </head>
// <body>
//     <div id="app"></div>
// </body>
// </html>`);
// 请求接口
// const document = dom.window.document;
// fetch 18版本之后才有的
var timmer = 0;
var max = 100;
downloadByNumber(max)
function downloadByNumber(max,lazyTime=1000){

    https.get("https://api.52vmy.cn/api/img/tu/mo",function(res){
        res.on('data', (d) => {
            var buf = Buffer.from(d);
            let ress = JSON.parse(buf.toString());
            if (ress.code==200) {
                let {url} = ress;
                var arr = ress.url.split("/");
                let filename = arr.pop();
                let path = filename;
                console.log(url);
                https.get(url,function (req,res) {
                    var imgData = '';
                    req.on('data',function (chunk) {
                        imgData += chunk;
                    })
                    req.setEncoding('binary');
                    req.on('end',function () {
                        fs.writeFile("./image/"+path,imgData,'binary',function (err) {
                            console.log(`成功保存第${timmer + 1}张图片`+path)
                            timmer++;
                            if (timmer<20) {
                                setTimeout(function(){

                                    downloadByNumber(timmer)
                                },lazyTime)
                            }
                        })
                    })
                })
            
            }
            
          });
    })
}
